package com.zebraphp.devtool.httpUtils.NetOkHttp.responseHandler;

import com.google.gson.Gson;
import com.google.gson.internal.$Gson$Types;
import com.zebraphp.devtool.httpUtils.NetOkHttp.IOkHttp;
import com.zebraphp.devtool.util.ILog;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Gson类型的回调接口
 * Created by tsy on 16/8/15.
 */
public abstract class GsonParseHandler<T> implements BaseHandler {

    private Type mType;

    private Type getType() {
        return mType;
    }

    /*对onOk的 Response 进行Gson二次解析*/
    public abstract void onOkParse(int statusCode, T responseBean);

    public GsonParseHandler() {
        Type myclass = getClass().getGenericSuperclass();    //反射获取带泛型的class
        if (myclass instanceof Class) {
            throw new RuntimeException("Missing type parameter.");
        }
        ParameterizedType parameter = (ParameterizedType) myclass;      //获取所有泛型
        mType = $Gson$Types.canonicalize(parameter.getActualTypeArguments()[0]);  //将泛型转为type
    }

    @Override
    public final void onOk(final Response response) {
        ResponseBody responseBody = response.body();
        String responseBodyStr = "";

        try {
            responseBodyStr = responseBody.string();
        } catch (IOException e) {
            e.printStackTrace();

            ILog.printLib("onResponse fail read response body");
            IOkHttp.mHandlerQueue.post(new Runnable() {
                @Override
                public void run() {
                    onError(response.code(), "fail read response body");
                }
            });
            return;
        } finally {
            responseBody.close();
        }

        final String finalResponseBodyStr = responseBodyStr;

        try {
            IOkHttp.mHandlerQueue.post(new Runnable() {
                @Override
                public void run() {
                    Gson gson = new Gson();
                    onOkParse(response.code(), (T) gson.fromJson(finalResponseBodyStr, getType()));
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            IOkHttp.mHandlerQueue.post(new Runnable() {
                @Override
                public void run() {
                    onError(response.code(), "Gson解析失败,原始内容:" + finalResponseBodyStr);
                }
            });
        }
    }

    /*
    由于子类 除了下载的时候使用这个函数，
    一般很少使用这个函数 所以提前实现，子类可以省去这个函数显示
     */
    @Override
    public void onProgress(long currentBytes, long totalBytes) {

    }
}
